﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Helpers
{
    using System;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Threading.Tasks;
    using Windows.Storage;
    using Windows.Storage.Streams;

    public static class StateHelper
    {
        public static async Task<bool> SaveObject(object o, StorageFolder storageFolder, string fileName)
        {
            bool success = false;
            try
            {
                MemoryStream data = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(o.GetType());
                serializer.WriteObject(data, o);
            
                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    data.Seek(0, SeekOrigin.Begin);
                    await data.CopyToAsync(fileStream);
                    await fileStream.FlushAsync();
                }
                success = true;
            }
            catch (Exception ex)
            {
                DebugHelper.Fail(ex);                
            }

            return success;
        }

        public static async Task<T> LoadObject<T>(StorageFolder storageFolder, string fileName)
        {
            T value = default(T);

            try
            {
                // Get the input stream for the SessionState file
                StorageFile file = await storageFolder.GetFileAsync(fileName);
                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    // Deserialize the Session State
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    value = (T) serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            catch (Exception ex)
            {
             //   DebugHelper.Fail(ex);                
            }

            return value;
        }
    }
}
